<template>
  <div class="inbound-management">
    <div class="page-header">
      <h2>入库管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索条件区域 -->
    <el-card class="search-card">
      <template #header>
        <span>搜索条件</span>
        <el-button type="text" @click="resetSearch" style="float: right;">重置</el-button>
      </template>
      
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户代码">
              <el-select v-model="searchForm.customerCode" filterable
                         placeholder="选择客户代码" clearable style="width: 100%;"
                         @change="handleSearchCustomerCodeChange">
                <el-option v-for="customer in customers" :key="customer.customerCode"
                          :label="customer.customerCode" :value="customer.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-select v-model="searchForm.customerName" filterable
                         placeholder="选择客户名称" clearable style="width: 100%;"
                         @change="handleSearchCustomerNameChange">
                <el-option v-for="customer in customers" :key="customer.customerName"
                          :label="customer.customerName" :value="customer.customerName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="searchForm.productName" placeholder="产品名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编码">
              <el-input v-model="searchForm.materialCode" placeholder="物料编码" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务员">
                            <el-select v-model="searchForm.salesperson" filterable allow-create default-first-option
                         placeholder="选择或输入业务员" clearable style="width: 100%;">
                <el-option v-for="emp in employees" :key="emp.employeeCode"
                           :label="emp.employeeName" :value="emp.employeeName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否含税">
              <el-select v-model="searchForm.isTaxIncluded" placeholder="选择是否含税" clearable style="width: 100%;">
                <el-option label="否" :value="false"/>
                <el-option label="增值税票 13%" :value="true"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单日期">
              <el-date-picker 
                v-model="searchForm.dateRange" 
                type="daterange" 
                range-separator="至" 
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商代码">
              <el-input v-model="searchForm.supplierCode" placeholder="供应商代码" clearable/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 可入库外发单列表 -->
    <el-card class="table-card">
      <template #header>
        <span>可入库外发单列表</span>
        <span style="color: #999; font-size: 14px; margin-left: 10px;">
          (显示已回厂状态的外发单)
        </span>
      </template>

      <el-table 
        :data="outsourcingList" 
        border 
        v-loading="loading"
        height="500"
        style="width: 100%">
        
        <el-table-column type="index" label="序号" width="60" fixed="left"/>
        
        <el-table-column prop="outsourcingNo" label="外发单号" width="140" fixed="left"/>
        <el-table-column prop="quotationNo" label="报价单号" width="140" fixed="left"/>
        <el-table-column prop="supplierCode" label="供应商代码" width="120" fixed="left"/>
        <el-table-column prop="supplierName" label="供应商名称" width="150" fixed="left"/>
        <el-table-column prop="status" label="状态" width="100" fixed="left">
          <template #default="{ row }">
            <el-tag type="success" size="small">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleInbound(row)">
              入库
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="productName" label="产品名称" width="150"/>
        <el-table-column prop="materialCode" label="物料编码" width="120"/>
        <el-table-column prop="quantity" label="外发数量" width="100" align="right">
          <template #default="{ row }">
            <span style="color: #E6A23C; font-weight: bold;">{{ row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="外发单价" width="100" align="right">
          <template #default="{ row }">
            <span>¥{{ (row.unitPrice || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="外发总金额" width="120" align="right">
          <template #default="{ row }">
            <span style="color: #E6A23C; font-weight: bold;">
              ¥{{ (row.totalAmount || 0).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="outsourcingDate" label="外发日期" width="120"/>
        <el-table-column prop="actualReturnDate" label="回厂日期" width="120"/>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip/>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 入库操作对话框 -->
    <el-dialog
      v-model="inboundDialogVisible"
      title="入库操作"
      width="80%"
      :before-close="handleCloseInboundDialog">
      
      <el-form :model="inboundForm" :rules="inboundRules" ref="inboundFormRef" label-width="120px">
        <!-- 基本信息 -->
        <el-card class="form-section" style="margin-bottom: 20px;">
          <template #header>
            <span>基本信息</span>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="外发单号">
                <el-input v-model="inboundForm.outsourcingNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="报价单号">
                <el-input v-model="inboundForm.quotationNo" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商代码">
                <el-input v-model="inboundForm.supplierCode" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="供应商名称">
                <el-input v-model="inboundForm.supplierName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入库日期" prop="inboundDate">
                <el-date-picker
                  v-model="inboundForm.inboundDate"
                  type="date"
                  placeholder="选择入库日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="厂内编号" prop="factoryNo">
                <el-input v-model="inboundForm.factoryNo" placeholder="系统自动生成" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 物料详情 -->
        <el-card class="form-section" style="margin-bottom: 20px;">
          <template #header>
            <span>物料入库详情</span>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产品名称">
                <el-input v-model="inboundForm.productName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料编码">
                <el-input v-model="inboundForm.materialCode" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外发数量">
                <el-input v-model="inboundForm.outsourcingQuantity" readonly>
                  <template #suffix>
                    <span style="color: #999;">PCS</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="入库数量" prop="inboundQuantity">
                <el-input
                  v-model.number="inboundForm.inboundQuantity"
                  type="number"
                  :min="0"
                  :max="inboundForm.outsourcingQuantity"
                  placeholder="入库数量"
                  @input="handleInboundQuantityChange">
                  <template #suffix>
                    <span style="color: #999;">PCS</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备品数量">
                <el-input
                  v-model.number="inboundForm.spareQuantity"
                  type="number"
                  :min="0"
                  placeholder="备品数量"
                  @input="handleSpareQuantityChange">
                  <template #suffix>
                    <span style="color: #999;">PCS</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总入库数量">
                <el-input :value="getTotalInboundQuantity()" readonly>
                  <template #suffix>
                    <span style="color: #999;">PCS</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="外发单价">
                <el-input :value="`¥${(inboundForm.unitPrice || 0).toFixed(2)}`" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外发总金额">
                <el-input :value="`¥${(inboundForm.totalAmount || 0).toFixed(2)}`" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 入库汇总 -->
        <el-card class="form-section">
          <template #header>
            <span>入库汇总</span>
          </template>
          
          <el-form-item label="备注">
            <el-input
              v-model="inboundForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入入库备注信息" />
          </el-form-item>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseInboundDialog">取消</el-button>
          <el-button type="primary" @click="confirmInbound" :loading="loading">
            确认入库
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { outsourcingAPI, customerAPI, employeeAPI, inboundAPI } from '../utils/api'
import { Search, Refresh, RefreshLeft } from '@element-plus/icons-vue'

export default {
  name: 'InboundManagement',
  components: {
    Search,
    Refresh,
    RefreshLeft
  },
  setup() {
    const loading = ref(false)
    const inboundDialogVisible = ref(false)
    const inboundFormRef = ref(null)

    // 搜索表单
    const searchForm = reactive({
      customerCode: '',
      customerName: '',
      productName: '',
      materialCode: '',
      salesperson: '',
      isTaxIncluded: null,
      dateRange: [],
      supplierCode: ''
    })

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }

    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 外发单列表
    const outsourcingList = ref([])
    
    // 基础数据
    const customers = ref([])
    const employees = ref([])
    
    // 入库表单数据
    const inboundForm = reactive({
      outsourcingId: null,
      outsourcingNo: '',
      quotationNo: '',
      supplierCode: '',
      supplierName: '',
      productName: '',
      materialCode: '',
      outsourcingQuantity: 0,
      unitPrice: 0,
      totalAmount: 0,
      inboundDate: new Date().toISOString().split('T')[0],
      factoryNo: '',
      inboundQuantity: 0,
      spareQuantity: 0,
      remark: ''
    })
    
    // 入库表单验证规则
    const inboundRules = {
      inboundDate: [
        { required: true, message: '请选择入库日期', trigger: 'change' }
      ],
      factoryNo: [
        { required: true, message: '请输入厂内编号', trigger: 'blur' }
      ],
      inboundQuantity: [
        { required: true, message: '请输入入库数量', trigger: 'blur' },
        { type: 'number', min: 0, message: '入库数量不能小于0', trigger: 'blur' }
      ]
    }

    // 计算属性：搜索参数
    const searchParams = computed(() => {
      const params = {
        current: pagination.current,
        size: pagination.size,
        ...searchForm
      }
      
      // 处理日期范围
      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        params.startDate = searchForm.dateRange[0]
        params.endDate = searchForm.dateRange[1]
      }
      delete params.dateRange
      
      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })
      
      return params
    })

    // 获取可入库外发单列表
    const fetchOutsourcingList = async () => {
      try {
        loading.value = true
        const response = await outsourcingAPI.getAvailableOutsourcingForInbound(searchParams.value)
        
        if (response.code === 200) {
          outsourcingList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('获取外发单列表失败:', error)
        ElMessage.error('获取外发单列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取基础数据
    const fetchBaseData = async () => {
      try {
        const [customerRes, employeeRes] = await Promise.all([
          customerAPI.getAllCustomers(),
          employeeAPI.getAllEmployees()
        ])
        
        if (customerRes.code === 200) {
          customers.value = customerRes.data || []
        }
        
        if (employeeRes.code === 200) {
          employees.value = employeeRes.data || []
        }
      } catch (error) {
        console.error('获取基础数据失败:', error)
        ElMessage.error('获取基础数据失败')
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchOutsourcingList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        customerCode: '',
        customerName: '',
        productName: '',
        materialCode: '',
        salesperson: '',
        isTaxIncluded: null,
        dateRange: [],
        supplierCode: ''
      })
      pagination.current = 1
      fetchOutsourcingList()
    }

    // 刷新数据
    const refreshData = () => {
      fetchOutsourcingList()
    }

    // 分页变化
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      fetchOutsourcingList()
    }

    const handleCurrentChange = (val) => {
      pagination.current = val
      fetchOutsourcingList()
    }

    // 入库操作 - 打开入库对话框
    const handleInbound = async (row) => {
      try {
        // 重置入库表单
        Object.assign(inboundForm, {
          outsourcingId: row.id,
          outsourcingNo: row.outsourcingNo,
          quotationNo: row.quotationNo,
          supplierCode: row.supplierCode,
          supplierName: row.supplierName,
          productName: row.productName,
          materialCode: row.materialCode,
          outsourcingQuantity: row.quantity,
          unitPrice: row.unitPrice,
          totalAmount: row.totalAmount,
          inboundDate: new Date().toISOString().split('T')[0],
          factoryNo: '',
          inboundQuantity: row.quantity, // 默认入库数量等于外发数量
          spareQuantity: 0, // 默认备品数量为0
          remark: ''
        })
        
        // 生成厂内编号
        try {
          const factoryNoResponse = await inboundAPI.generateFactoryNo()
          if (factoryNoResponse.code === 200) {
            inboundForm.factoryNo = factoryNoResponse.data
          }
        } catch (error) {
          console.warn('自动生成厂内编号失败:', error)
        }
        
        // 显示入库对话框
        inboundDialogVisible.value = true
      } catch (error) {
        console.error('获取外发单详情失败:', error)
        ElMessage.error('获取外发单详情失败')
      }
    }

    // 关闭入库对话框
    const handleCloseInboundDialog = () => {
      inboundDialogVisible.value = false
      // 重置表单
      if (inboundFormRef.value) {
        inboundFormRef.value.resetFields()
      }
    }

    // 入库数量变化处理
    const handleInboundQuantityChange = () => {
      // 确保数值为正数
      if (inboundForm.inboundQuantity < 0) {
        inboundForm.inboundQuantity = 0
      }
      // 确保是整数
      if (inboundForm.inboundQuantity && !Number.isInteger(inboundForm.inboundQuantity)) {
        inboundForm.inboundQuantity = Math.floor(inboundForm.inboundQuantity)
      }
      // 确保不超过外发数量
      if (inboundForm.inboundQuantity > inboundForm.outsourcingQuantity) {
        inboundForm.inboundQuantity = inboundForm.outsourcingQuantity
        ElMessage.warning('入库数量不能超过外发数量')
      }
    }

    // 备品数量变化处理
    const handleSpareQuantityChange = () => {
      // 确保数值为正数
      if (inboundForm.spareQuantity < 0) {
        inboundForm.spareQuantity = 0
      }
      // 确保是整数
      if (inboundForm.spareQuantity && !Number.isInteger(inboundForm.spareQuantity)) {
        inboundForm.spareQuantity = Math.floor(inboundForm.spareQuantity)
      }
    }

    // 计算总入库数量
    const getTotalInboundQuantity = () => {
      return (inboundForm.inboundQuantity || 0) + (inboundForm.spareQuantity || 0)
    }

    // 确认入库
    const confirmInbound = async () => {
      try {
        // 表单验证
        if (!inboundFormRef.value) return
        const valid = await inboundFormRef.value.validate()
        if (!valid) return

        // 检查是否有入库数量
        const totalInbound = getTotalInboundQuantity()
        if (totalInbound === 0) {
          ElMessage.warning('请至少输入入库数量或备品数量')
          return
        }

        // 确认操作
        await ElMessageBox.confirm(
          `确认入库操作吗？\n外发单号：${inboundForm.outsourcingNo}\n外发数量：${inboundForm.outsourcingQuantity}\n入库数量：${inboundForm.inboundQuantity}\n备品数量：${inboundForm.spareQuantity}\n总入库数量：${totalInbound}`,
          '确认入库',
          {
            confirmButtonText: '确认入库',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        loading.value = true

        // 准备入库数据
        const inboundRequest = {
          outsourcingId: inboundForm.outsourcingId,
          outsourcingNo: inboundForm.outsourcingNo,
          quotationNo: inboundForm.quotationNo,
          supplierCode: inboundForm.supplierCode,
          supplierName: inboundForm.supplierName,
          productName: inboundForm.productName,
          materialCode: inboundForm.materialCode,
          outsourcingQuantity: inboundForm.outsourcingQuantity,
          inboundQuantity: inboundForm.inboundQuantity || 0,
          spareQuantity: inboundForm.spareQuantity || 0,
          totalInboundQuantity: totalInbound,
          unitPrice: inboundForm.unitPrice,
          totalAmount: inboundForm.totalAmount,
          inboundDate: inboundForm.inboundDate,
          factoryNo: inboundForm.factoryNo,
          remark: inboundForm.remark
        }

        // 调用入库API
        const response = await inboundAPI.createOutsourcingInbound(inboundRequest)
        
        if (response.code === 200) {
          ElMessage.success('入库成功')
          handleCloseInboundDialog()
          fetchOutsourcingList() // 刷新列表
        } else {
          console.error('入库失败:', response.message)
          ElMessage.error(response.message || '入库操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('入库失败:', error)
          ElMessage.error('入库失败')
        }
      } finally {
        loading.value = false
      }
    }

    // 搜索表单-客户代码变化处理
    const handleSearchCustomerCodeChange = (customerCode) => {
      const customer = customers.value.find(c => c.customerCode === customerCode)
      if (customer) {
        searchForm.customerName = customer.customerName
      }
    }

    // 搜索表单-客户名称变化处理
    const handleSearchCustomerNameChange = (customerName) => {
      const customer = customers.value.find(c => c.customerName === customerName)
      if (customer) {
        searchForm.customerCode = customer.customerCode
      }
    }

    // 初始化
    onMounted(() => {
      fetchBaseData()
      fetchOutsourcingList()
    })

    return {
      loading,
      searchForm,
      pagination,
      outsourcingList,
      customers,
      employees,
      inboundDialogVisible,
      inboundForm,
      inboundRules,
      inboundFormRef,
      formatDate,
      handleSearch,
      resetSearch,
      refreshData,
      handleSizeChange,
      handleCurrentChange,
      handleInbound,
      handleCloseInboundDialog,
      handleInboundQuantityChange,
      handleSpareQuantityChange,
      getTotalInboundQuantity,
      confirmInbound,
      handleSearchCustomerCodeChange,
      handleSearchCustomerNameChange
    }
  }
}
</script>

<style scoped>
.inbound-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-table {
  font-size: 14px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

/* 已移除不必要的数字输入框样式 */

/* 弹窗样式优化 */
.full-width-input {
  width: 100% !important;
}

.important-field {
  margin-bottom: 20px;
}

.important-field :deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

.dialog-footer .el-button {
  margin-left: 10px;
  min-width: 80px;
}

/* 弹窗内表单优化 */
:deep(.el-dialog__body) {
  padding: 20px 25px;
  max-height: 80vh;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-date-editor.el-input) {
  width: 100% !important;
}

:deep(.el-select) {
  width: 100% !important;
}

/* 确保普通输入框正常显示 */
:deep(.el-input) {
  width: 100% !important;
}

:deep(.el-input__wrapper) {
  width: 100% !important;
}

/* 弹窗响应式处理 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px 20px;
  }
}
</style> 